package com.xqboss.framework.config;

import com.xqboss.common.config.properties.RocketMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @Author jjj
 */
@Slf4j
@Configuration
public class MQProducer {

    @Resource
    private RocketMqConfig rocketMqConfig;


    @Bean
    public Producer defaultProducer() throws ClientException {
        if(BooleanUtils.isNotTrue(rocketMqConfig.getEnable())){
            log.warn("未开启rocketMq");
            return null;
        }
        SessionCredentialsProvider sessionCredentialsProvider =
                new StaticSessionCredentialsProvider(rocketMqConfig.getAccessKey(), rocketMqConfig.getSecretKey());
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
                .setEndpoints(rocketMqConfig.getNameSrvAddr())
                .setCredentialProvider(sessionCredentialsProvider)
                .build();
        final ClientServiceProvider provider = ClientServiceProvider.loadService();
        Producer build = provider.newProducerBuilder().setClientConfiguration(clientConfiguration).build();
        return build;
    }
}
